import { app, BrowserWindow, ipcMain, nativeTheme } from 'electron'
import path from 'path'
import os from 'os'


// needed in case process is undefined under Linux
const platform = process.platform || os.platform()

try {
  if (platform === 'win32' && nativeTheme.shouldUseDarkColors === true) {
    require('fs').unlinkSync(path.join(app.getPath('userData'), 'DevTools Extensions'))
  }
}
catch (_) { }

let mainWindow
let newConnectionWindow



function createWindow () {
  /**
   * Initial window options
   */
  mainWindow = new BrowserWindow({
    icon: path.resolve(__dirname, 'icons/icon.png'), // tray icon
    width: 1300,
    height: 800,
    frame: false,
    transparent: true,
    hasShadow: false,
    maximizable: true,
    webPreferences: {
      contextIsolation: true,
      nodeIntegration: process.env.QUASAR_NODE_INTEGRATION,
      nodeIntegrationInWorker: process.env.QUASAR_NODE_INTEGRATION,
      // More info: /quasar-cli/developing-electron-apps/electron-preload-script
      preload: path.resolve(__dirname, process.env.QUASAR_ELECTRON_PRELOAD)
    }
  })
  mainWindow.loadURL(process.env.APP_URL)

  if (process.env.DEBUGGING) {
    // if on DEV or Production with debug enabled
    // mainWindow.webContents.openDevTools()
  }
  else {
    // we're on production; no access to devtools pls
    mainWindow.webContents.on('devtools-opened', () => {
      // mainWindow.webContents.closeDevTools()
    })
  }

/*
  newConnectionWindow = new BrowserWindow({
    parent: mainWindow,
    modal: true,
    autoHideMenuBar: true,
    resizable: false,
    frame: false,
    transparent: true,
    hasShadow: false,
    fullscreenable: false,
    maximizable: false,
    minimizable: false,
    webPreferences: {
      nodeIntegration: true, //默认是false
      contextIsolation: true,
      nodeIntegrationInWorker: process.env.QUASAR_NODE_INTEGRATION,
    }
  })
  newConnectionWindow.loadURL(process.env.APP_URL)
  newConnectionWindow.hide()
*/


  mainWindow.on('closed', () => {
    mainWindow = null
  })

}

app.whenReady().then(createWindow)

app.on('window-all-closed', () => {
  if (platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', () => {
  if (mainWindow === null) {
    createWindow()
    document.getElementById("app-quit").addEventListener("click", function (e) {
      remote.getCurrentWindow().close()
    })
  }
})


ipcMain.on('window-min', () => {
  if (mainWindow && !mainWindow.isDestroyed()){
    mainWindow.minimize()
  }
})

ipcMain.on('window-toggle-max', (event)=> {
  if (mainWindow && !mainWindow.isDestroyed()){
    if (mainWindow.isMaximized()) {
      mainWindow.unmaximize()
      event.preventDefault()
    } else {
      mainWindow.maximize()
      event.preventDefault()
    }
  }
})

ipcMain.on('window-close', (event) => {
  if (platform !== 'darwin') {
    app.quit()
  }
})


ipcMain.on('new-connection-window', (event) => {
  console.log('on new-connection-window')
  newConnectionWindow.show()
})
